package com.dongzili.easyes.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dongzili.easyes.common.mybatisplus.MybatisPlusUtil;
import com.dongzili.easyes.common.mybatisplus.PropertyQueryWrapper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Deprecated
public class MpSqlHelper {

    @Deprecated
    public static <T> String getSelectListSQL(PropertyQueryWrapper<T> ew, Class<T> entityClass) {

        // wrapper 会作为参数传入 mapper
        Map<String, Object> params = Collections.singletonMap("ew", ew);

        SqlSessionFactory sqlSessionFactory = SpringUtil.getBean(SqlSessionFactory.class);
        // sqlSessionFactory 从 Spring 容器中获得
        Configuration configuration = sqlSessionFactory.getConfiguration();

        String mapperClassName = MybatisPlusUtil.getMapperName(entityClass);
        // 使用类引用+方法名得到 mapper 语句
        MappedStatement mappedStatement = configuration.getMappedStatement(mapperClassName+ ".selectList");
        BoundSql boundSql = mappedStatement.getBoundSql(params);

        String sql = getExecuteSql(boundSql, params);
        System.out.println(sql);
        return sql;
    }
    @Deprecated
    public static <T> String getSelectListSQL(QueryWrapper<T> ew, Class<T> entityClass) {

        // wrapper 会作为参数传入 mapper
        Map<String, Object> params = Collections.singletonMap("ew", ew);

        SqlSessionFactory sqlSessionFactory = SpringUtil.getBean(SqlSessionFactory.class);
        // sqlSessionFactory 从 Spring 容器中获得
        Configuration configuration = sqlSessionFactory.getConfiguration();

        String mapperClassName = MybatisPlusUtil.getMapperName(entityClass);
        // 使用类引用+方法名得到 mapper 语句
        MappedStatement mappedStatement = configuration.getMappedStatement(mapperClassName+ ".selectList");
        BoundSql boundSql = mappedStatement.getBoundSql(params);

        String sql = getExecuteSql(boundSql, params);
        System.out.println(sql);
        return sql;
    }

    private static String getExecuteSql(BoundSql boundSql, Object paramObject) {
        // 带有问号占位符的 SQL 语句
        String sql = boundSql.getSql();
        // 参数信息列表
        List<ParameterMapping> paramMappings = boundSql.getParameterMappings();
        SqlSessionFactory sqlSessionFactory = SpringUtil.getBean(SqlSessionFactory.class);
        // MetaObject 是 mybatis 通过表达式取出对象内容的工具
        MetaObject metaObject = sqlSessionFactory.getConfiguration().newMetaObject(paramObject);
        for (ParameterMapping p : paramMappings) {
            String paramName = p.getProperty();
            Object paramValue = metaObject.getValue(paramName);
            String value = ""+paramValue;
            if (paramValue instanceof String) {
                value = "'" + paramValue + "'";
            }
            sql = sql.replaceFirst("\\?", value);
        }
        return sql;
    }

//    /**
//     * 强制 TableInfo 中的列名使用实体类字段名（忽略 @TableField(value)）
//     */
//    public static <T> void forceFieldNameAsColumnName(Class<T> entityClass) {
//        // 获取 MP 自动解析的 TableInfo
//        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
//        if (tableInfo == null) {
//            throw new RuntimeException("实体类未注册：" + entityClass.getName());
//        }
//
//        // 反射获取 TableInfo 中的字段信息列表（tableFieldList）
//        try {
//            Field tableFieldListField = TableInfo.class.getDeclaredField("fieldList");
//            tableFieldListField.setAccessible(true);
//            List<TableFieldInfo> tableFieldList = (List<TableFieldInfo>) tableFieldListField.get(tableInfo);
//
//            // 遍历所有字段，强制列名 = 实体类字段名
//            for (TableFieldInfo fieldInfo : tableFieldList) {
//                // 反射修改 TableFieldInfo 中的 column 属性（数据库列名）
//                Field columnField = TableFieldInfo.class.getDeclaredField("column");
//                columnField.setAccessible(true);
//                // 实体类字段名（fieldInfo.getProperty() 就是实体类字段名）
//                String fieldName = fieldInfo.getProperty();
//                columnField.set(fieldInfo, fieldName);
//            }
//        } catch (Exception e) {
//            throw new RuntimeException("强制字段名映射失败", e);
//        }
//    }
}
